package com.zbkj.admin.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zbkj.admin.service.WechatService;
import com.zbkj.admin.service.WechatWxaSecOrderInfoService;
import com.zbkj.admin.third_party.BracketSetApi;
import com.zbkj.admin.third_party.vo.BracketSetVo;
import com.zbkj.admin.third_party.vo.DataDTOX;
import com.zbkj.admin.vo.WeChatOauthToken;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.concurrent.CompletableFuture;


/**
 * @params 对接 微信订单发货接口 服务
 * @date 2025-04-17
 * @author llc
 */
@Service
public class WechatWxaSecOrderServiceImpl implements WechatWxaSecOrderInfoService {

    @Resource
    private WechatService wechatService;
    @Autowired
    private BracketSetApi bracketSetApi;

    /**
     * @params 发货信息录入 - 推送微信
     * @date 2025-04-17
     * @author llc
     * @param mchId          商户号
     * @param outTradeNo     商户订单号
     * @param accessToken    accessToken
     * @param openid         买家openid
     * @param expressCompany 快递公司编码
     * @param trackingNo     快递单号
     */
    @Override
    public void uploadShippingInfo(String orderNo) {
        // 获取微信小程序token
        String accessToken = wechatService.getMiniAccessToken();

        CompletableFuture<JSONObject> json = bracketSetApi.query(orderNo);
        try {
            JSONObject json1  = json.get();
            System.out.println(json1);
        }catch (Exception e){
            e.printStackTrace();
        }
//        // 通过code获取获取公众号授权信息
//        WeChatOauthToken oauthToken = wechatService.getOauth2AccessToken(request.getCode());



        JSONObject orderKey = new JSONObject();
        // 订单单号类型，用于确认需要上传详情的订单。枚举值1，使用下单商户号和商户侧单号；枚举值2，使用微信支付单号。
        orderKey.put("order_number_type", 1);
        // 商户号
        orderKey.put("mchid", "759859892");
        // 微信支付订单号
//        orderKey.put("transaction_id",transactionId);
        // 商户订单号
        orderKey.put("out_trade_no", "WX613174400200962278792");

        JSONObject shippingList = new JSONObject();
        //商品信息
        shippingList.put("item_desc", "12123");
        //物流单号，物流快递发货时必填
        shippingList.put("tracking_no", "9806549757699");
        // 快递公司编码，物流快递发货时必填
        shippingList.put("express_company", "YZ");

        JSONObject payer = new JSONObject();
        payer.put("openid", "oR-Gl7eEBmAnGCl4droz6Yy8UMo4"); // 买家openid

        JSONObject signObject = new JSONObject();
        JSONArray shipping_list = new JSONArray();
        shipping_list.add(shippingList);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String uploadTime = simpleDateFormat.format(System.currentTimeMillis());

        signObject.put("order_key", orderKey);
        // 发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）2、SPLIT_DELIVERY（分拆发货） 示例值: 1
        signObject.put("delivery_mode", 1);
        // 物流模式，发货方式枚举值：1、实体物流配送采用快递公司进行实体物流配送形式 2、同城配送 3、虚拟商品，虚拟商品，例如话费充值，点卡等，无实体配送形式 4、用户自提
        signObject.put("logistics_type", 1);
        signObject.put("shipping_list", shipping_list);
        signObject.put("upload_time", uploadTime);
        signObject.put("payer", payer);
        System.out.println("发货信息：" + signObject.toString());

        // 拼接微信参数 - 发货信息录入接口
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentLength(signObject.toString().getBytes().length);
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);

        // 构建包含请求体数据和请求头的HttpEntity对象
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(signObject, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String errcode = jsonObject.getStr("errcode");
        System.out.println("errcode：" + body);
    }
}

